package com.lc.lc692;

import java.util.*;

public class Main {
	
	public static void main(String[] args) {
		
	}

}


class Solution {
    public List<String> topKFrequent(String[] words, int k) {
        Map<String, Integer> mp = new HashMap<>();
        int n = words.length;
        for (int i = 0; i < n; i ++) {
        	mp.put(words[i], mp.getOrDefault(words[i], 0) + 1);
        }
        List<String> list = new ArrayList<>();
        for (String s: mp.keySet()) {
        	list.add(s);
        }
        
        list.sort(new Comparator<String>() {

			@Override
			public int compare(String s1, String s2) {
				if (mp.get(s1) == mp.get(s2)) {
					return s1.compareTo(s2);
				} else {
					return mp.get(s2) - mp.get(s1);
				}
			}
		});
        return list.subList(0, k);
    }
}